//
//  MenuViewController.m
//  Menu
//
//  Created by trimad on 11-11-11.
//  Copyright 2011 Trimad Group. All rights reserved.
//

#import <QuartzCore/QuartzCore.h>

#import "MenuViewController.h"
#import "PageViewController.h"
#import "PageLayoutView.h"
#import "TopCategoryButton.h"
#import "SubCategoryButton.h"
#import "Category.h"
#import "Item.h"
#import "Page.h"
#import "Order.h"
#import "OrderItem.h"
#import "DisplayManager.h"
#import "OrderManager.h"

#import "OneBlockBoxStyle1View.h"
#import "TwoBlockBoxStyle1View.h"
#import "TwoBlockBoxStyle2View.h"
#import "ThreeBlockBoxStyle1View.h"
#import "ThreeBlockBoxStyle2View.h"
#import "FourBlockBoxStyleView.h"
#import "SixBlockBoxStyleView.h"
#import "NineBlockBoxView.h"
#import "LayoutAd1View.h"
#import "OrderInHandViewController.h"
#import "SearchViewController.h"
#import "ContextManager.h"
#import "CoverViewController.h"

@interface MenuViewController(Private)
/*
 * 捕捉向右滑动事件，应跳转到上一页（如果有）
 */
- (void) handleSwipeRight:(UIGestureRecognizer *) sender;
/*
 * 捕捉向右滑动事件，应跳转到下一页 (如果有)
 */
- (void) handleSwipeLeft:(UIGestureRecognizer *) sender;
/*
 * 通过页数得到此页的Page view controller.
 */
- (PageViewController *) getPageViewControllerByPageNum: (int) pageNum;
-(void)drawScrollPageView;
-(void)scrollToPage;

/*********************按钮相关方法**********************/
/*
 * 在主页面渲染时，初始化一级类别按钮
 */
- (void)initTopCategoryButtons;
- (void)initSubCategoryButtons:(Category *)topCategory;
/*
 * 捕捉一级类别按钮点击事件，这将跳转到相应的页面中去。
 */
-(void)topCategoryButtonClicked:(id)sender;
-(void)subCategoryButtonClicked:(id)sender;
/*
 * 在一级类别按钮将失去选择后调用此方法，按钮样式将发生变化
 */
-(void)unselectTopCategoryButton:(TopCategoryButton *)topCategoryButton;
-(void)unselectSubCategoryButton:(UIButton *)subCategoryButton;
/*
 * 调用此方法将某一一级类别按钮选中，按钮样式将发生变化
 * 
 * 返回值用以说明是否选中成功
 */
-(BOOL)selectTopCategoryButton:(TopCategoryButton *)topCategoryButton;
-(BOOL)selectSubCategoryButton:(UIButton *)subCategoryButton;
/*
 * 此方法主要用于类别按钮的联动，当要跳转到某一页面时，类别按钮可能需要相应变化
 */
-(void)switchButton:(int)toBeSelectedPageIndex;

-(NSMutableArray *)mockUpAd1;

@end

@implementation MenuViewController

@synthesize pageScrollView;
@synthesize topCategoryLabel;
@synthesize orderInHandView;
@synthesize searchView;
@synthesize subCategoryBarImageView;

static int MAX_PAGES = 50;
static int PAGE_VIEW_WIDTH = 680;
static int PAGE_VIEW_HEIGHT = 850;
static int TOP_CATEGORY_X = 720;
static int TOP_CATEGORY_Y = 80;
static int TOP_CATEGORY_SPAN = 80;
static int SUB_CATEGORY_X = 688;
static int SUB_CATEGORY_Y = 60;
static int SUB_CATEGORY_SPAN = 80;

DisplayManager *dm = nil;
/*
 * 用来存放所有的PageViewController <pageNumber,PageViewController>
 */
NSMutableDictionary *pageViewControllerDic = nil;
// 用于Scroll View的显示
NSMutableArray *scrollablePageViewControllerArray = nil;
/*
 * <top_category_start_page, TopCategoryButton>
 */
NSMutableDictionary *topCategoryButtonDic = nil;
/*
 * <sub_category_start_page, SubCategoryButton>
 */
NSMutableDictionary *subCategoryButtonDic = nil;
PageViewController *currentPageViewController = nil;
TopCategoryButton *currentSelectedTopCategoryButton = nil;
SubCategoryButton *currentSelectedSubCategoryButton = nil;
int currentPageIndex;


// The designated initializer. Override to perform setup that is required before the view is loaded.
-(id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        currentPageIndex = 1;
    }
	MAX_PAGES = [DisplayManager instance].pages.count;
	dm = [DisplayManager instance];
    return self;
}


// 初始化主框架及页面
-(void)viewDidLoad {
	// 1. Initialize Dictionary
	pageViewControllerDic = [[NSMutableDictionary alloc] initWithCapacity:MAX_PAGES];
	scrollablePageViewControllerArray = [[NSMutableArray alloc] initWithCapacity:MAX_PAGES];
	
	// 2. initialize category buttons
	[self initTopCategoryButtons];
	// 3. select the first top category
	[self selectTopCategoryButton:[topCategoryButtonDic 
								   objectForKey:[NSNumber numberWithInt:0]]];
	
	[self drawScrollPageView];
	[self scrollToPage];

}

-(void)drawScrollPageView {
	PageViewController *aPageViewController;
	for (int i = 0; i < MAX_PAGES; i++) {
		CGRect frame;
		frame.origin.x = PAGE_VIEW_WIDTH * i;
		frame.origin.y = 0;
		frame.size.height = PAGE_VIEW_HEIGHT;
		frame.size.width = PAGE_VIEW_WIDTH;
		
		aPageViewController = [self getPageViewControllerByPageNum:i];
		aPageViewController.view.frame = frame;
		[scrollablePageViewControllerArray addObject:aPageViewController];
		[self.pageScrollView addSubview:aPageViewController.view];
	}
	
	// 获取滚动View总宽度
	self.pageScrollView.contentSize = CGSizeMake(PAGE_VIEW_WIDTH * MAX_PAGES, 
											 PAGE_VIEW_HEIGHT);
}

-(void)scrollToPage{
	// 滚动到当前选中的PageView
	CGPoint point;
	point.x = PAGE_VIEW_WIDTH * currentPageIndex;
	point.y = 0;
	self.pageScrollView.contentOffset = point;
}

/* 每次滑动结束后进行预加载*/
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    // Update the page when more than 50% of the previous/next page is visible
    CGFloat pageWidth = PAGE_VIEW_WIDTH;
    currentPageIndex = floor((self.pageScrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
	PageViewController *pageViewController = [self getPageViewControllerByPageNum:currentPageIndex];
	if (pageViewController != nil) {
		currentPageViewController = pageViewController;
		
		[self scrollToPage];
		[self switchButton:currentPageIndex];
	}
}

/*
 * 通过页数得到此页的Page view controller.
 */
-(PageViewController *)getPageViewControllerByPageNum:(int)pageNum {
	PageViewController *pageViewController = [pageViewControllerDic 
										  objectForKey: [NSNumber numberWithInt:pageNum]];
	
	if (pageViewController == nil) {
		// 1. 根据meta数据找到并实例化一个PageLayoutView子类
		CGRect layoutFrame = CGRectMake(0, 0, PAGE_VIEW_WIDTH, PAGE_VIEW_HEIGHT);
		Page *page = [dm page:pageNum];
		if (page == nil) {
			return nil;
		}
		PageLayoutView *layout;
		LayoutAd1View *adLayout;
		NSArray *itemArray = page.items;
		switch (page.viewType) {
			case OneBlockBoxStyle1:
				layout = [[OneBlockBoxStyle1View alloc] 
						  initWithFrameAndItems:layoutFrame 
						  items:itemArray];
				break;
			case TwoBlockBoxStyle1:
				layout = [[TwoBlockBoxStyle1View alloc] 
						  initWithFrameAndItems:layoutFrame 
						  items:itemArray];
				break;
			case TwoBlockBoxStyle2:
				layout = [[TwoBlockBoxStyle2View alloc] 
						  initWithFrameAndItems:layoutFrame 
						  items:itemArray];
				break;
			case ThreeBlockBoxStyle1:
				layout = [[ThreeBlockBoxStyle1View alloc] 
						  initWithFrameAndItems:layoutFrame 
						  items:itemArray];
				break;
			case ThreeBlockBoxStyle2:
				layout = [[ThreeBlockBoxStyle2View alloc] 
						  initWithFrameAndItems:layoutFrame 
						  items:itemArray];
				break;
			case FourBlockBoxStyle:
				layout = [[FourBlockBoxStyleView alloc] 
						  initWithFrameAndItems:layoutFrame 
						  items:itemArray];
				break;
			case SixBlockBoxStyle:
				layout = [[SixBlockBoxStyleView alloc] 
						  initWithFrameAndItems:layoutFrame 
						  items:itemArray];
				break;
			case NineBlockBox:
				layout = [[NineBlockBoxView alloc] 
						  initWithFrameAndItems:layoutFrame 
						  items:itemArray];
				break;
				
			case AdStyle1:
				adLayout = [[[NSBundle mainBundle] loadNibNamed:@"LayoutAd1View" 
								   owner:self options:nil] objectAtIndex:0];
				[adLayout activate:[[self mockUpAd1] objectAtIndex:0]];
				layout = adLayout;
				break;
			default:
				return nil;
		}
		
		// 2. 根据新PageLayoutView创建PageViewController实例
		pageViewController = [[PageViewController alloc]
											  initWithNibAndLayout:@"PageViewController" 
											  bundle:nil 
											  pageLayout:layout];
		[pageViewControllerDic setObject:pageViewController forKey:[NSNumber numberWithInt:pageNum]];
	}
	return pageViewController;
}

- (NSMutableArray *)mockUpAd1 {
	NSMutableArray *items = [[NSMutableArray alloc] initWithCapacity:1];
	Item* item = [[Item alloc] init];
	item.itemType = AdItem;
	NSMutableArray *videoUrlArray = [[NSMutableArray alloc] initWithCapacity:1];
	NSString *url = [[NSBundle mainBundle] pathForResource:@"ad-video" ofType:@"mov"];
	[videoUrlArray addObject:url];
	item.adVideoUrlArray = videoUrlArray;
	
	NSMutableArray *imageArray = [[NSMutableArray alloc] initWithCapacity:1];
	NSString *imageString = @"ad-pic.jpg";
	[imageArray addObject:imageString];
	item.adImageArray = imageArray;
	[items addObject:item];
	return items;
}

/*
 * 捕捉点击订单预览按钮，弹出对话框显示
 */
-(IBAction)orderSummaryClicked:(id)sender {
	OrderInHandViewController *orderInHandViewController = [[OrderInHandViewController alloc] 
															initWithNibName:@"OrderInHandViewController" bundle:nil];
	orderInHandView.hidden = NO;
	[orderInHandView addSubview: orderInHandViewController.view];
}

-(IBAction)searchButtonClicked:(id)sender {
	SearchViewController *searchViewController = [[SearchViewController alloc] 
															initWithNibName:@"SearchViewController" bundle:nil];
	searchView.hidden = NO;
	[searchView addSubview: searchViewController.view];
}

/****************************按钮相关方法***************************/
/*
 * 在主页面渲染时，初始化一级类别按钮
 */
- (void)initTopCategoryButtons {
	NSArray *topCategoryArray = dm.topCategories;
	Category *aTopCategory = nil;
	TopCategoryButton * aButton = nil;
	CGPoint point;
	int x = TOP_CATEGORY_X, y;
	int count = [topCategoryArray count];
	topCategoryButtonDic = [[NSMutableDictionary alloc] initWithCapacity:count];
	
	for (int i = count - 1; i >= 0; i--) {
		y = TOP_CATEGORY_Y + i * TOP_CATEGORY_SPAN;
		point = CGPointMake(x, y);
		aTopCategory = [topCategoryArray objectAtIndex:i];
		aButton = [TopCategoryButton buttonWithType: UIButtonTypeCustom 
											  point:point 
										   category:aTopCategory];
		
		[aButton addTarget:self 
					action:@selector(topCategoryButtonClicked:) 
		  forControlEvents:UIControlEventTouchUpInside];
		
		// 以这种方式加快exchange Button的速度
		int start = [dm pageStart:aTopCategory.code];
		int end = [dm pageEnd:aTopCategory.code];
		for (int j = start; j <= end; j++) {
			[topCategoryButtonDic setObject:aButton 
									 forKey:[NSNumber numberWithInt:j]];
		}
		[self.view insertSubview:aButton belowSubview:subCategoryBarImageView];
	}
}

-(void)initSubCategoryButtons:(Category *)topCategory {
	if (subCategoryButtonDic != nil) {
		NSNumber *number;
		for (number in subCategoryButtonDic) {
			UIButton *aOriginalButton = [subCategoryButtonDic objectForKey:number];
			[aOriginalButton removeFromSuperview];
		}
		currentSelectedSubCategoryButton = nil;
		[subCategoryButtonDic release];
		subCategoryButtonDic = nil;
	}
	int count = [topCategory.subCategories count];
	subCategoryButtonDic = [[NSMutableDictionary alloc] 
							initWithCapacity:count];
	UIButton *aButton;
	
	Category *aSubCategory;
	int x = SUB_CATEGORY_X, y;
	for (int i = 0; i < count; i++) {;
		y = SUB_CATEGORY_Y + i * SUB_CATEGORY_SPAN;
		CGPoint aPoint = CGPointMake(x, y);
		
		aSubCategory = [topCategory.subCategories objectAtIndex:i];
		aButton = [SubCategoryButton buttonWithType: UIButtonTypeCustom 
											point:aPoint 
										   category:aSubCategory];
		int start = [dm pageStart:aSubCategory.code];
		int end = [dm pageEnd:aSubCategory.code];
		aButton.tag = start;
		[aButton addTarget:self 
					action:@selector(subCategoryButtonClicked:)
		  forControlEvents:UIControlEventTouchUpInside];
		
		// 以这种方式加快exchange Button的速度
		for (int j = start; j <= end; j++) {
			[subCategoryButtonDic setObject:aButton 
									 forKey:[NSNumber numberWithInt:j]];
		}
		
		[self.view addSubview:aButton];
	}
}

/*
 * 捕捉一级类别按钮点击事件，这将跳转到相应的页面中去。
 */
-(void)topCategoryButtonClicked:(id)sender {
	TopCategoryButton *topCategoryButton = sender;
	TopCategoryButton *originalSelectedButton = currentSelectedTopCategoryButton;
	if ([topCategoryButton isEqual:originalSelectedButton]) {
		return;
	}
	if ([self selectTopCategoryButton:topCategoryButton]) {
		[self unselectTopCategoryButton:originalSelectedButton];
	}
	
	[self scrollToPage];
}

-(void)subCategoryButtonClicked:(id)sender {
	UIButton *subCategoryButton = sender;
	UIButton *originalSelectedButton = currentSelectedSubCategoryButton;
	if ([subCategoryButton isEqual:originalSelectedButton]) {
		return;
	}
	if ([self selectSubCategoryButton:subCategoryButton]) {
		[self unselectSubCategoryButton:originalSelectedButton];
	}
	
	[self scrollToPage];
}

/*
 * 在一级类别按钮将失去选择后调用此方法，按钮样式将发生变化
 */
-(void)unselectTopCategoryButton:(TopCategoryButton *)topCategoryButton {
	[topCategoryButton toUnselectedState];
}

-(void)unselectSubCategoryButton:(SubCategoryButton *)subCategoryButton {
	[subCategoryButton toUnselectedState];
}

/*
 * 调用此方法将某一一级类别按钮选中，按钮样式将发生变化
 * 
 * 返回值用以说明是否选中成功
 */
-(BOOL)selectTopCategoryButton:(TopCategoryButton *)topCategoryButton {
	Category *firstSubCategory = [topCategoryButton.category.subCategories objectAtIndex:0];
	int pageIndex = [dm pageStart:firstSubCategory.code];
	PageViewController *pageViewController = [self getPageViewControllerByPageNum:pageIndex];
	if (pageViewController != nil) {
		currentPageIndex = pageIndex;
		currentSelectedTopCategoryButton = topCategoryButton;
		currentPageViewController = pageViewController;
		
		[topCategoryButton toSelectedState];
		[self initSubCategoryButtons:topCategoryButton.category];
		[self selectSubCategoryButton:
		 [subCategoryButtonDic objectForKey:[NSNumber numberWithInt:pageIndex]]];
		
		topCategoryLabel.text = currentSelectedTopCategoryButton.category.name;
		return YES;
		
	} else {
		return NO;
	}
}

-(BOOL)selectSubCategoryButton: (SubCategoryButton *)subCategoryButton {
	int pageIndex = subCategoryButton.tag;
	PageViewController *pageViewController = [self getPageViewControllerByPageNum:pageIndex];
	if (pageViewController != nil) {
		currentSelectedSubCategoryButton = subCategoryButton;
		if (currentPageIndex != pageIndex) {
			currentPageIndex = pageIndex;
			currentPageViewController = pageViewController;
		}
		
		[subCategoryButton toSelectedState];
		return YES;		
	} else {
		return NO;
	}
}


/*
 * 此方法主要用于类别按钮的联动，当要跳转到某一页面时，类别按钮可能需要相应变化
 */
-(void)switchButton:(int)toBeSelectedPageIndex {
	// switch top category buttons
	TopCategoryButton *toBeSelectedTopButton = [topCategoryButtonDic objectForKey:
													[NSNumber numberWithInt:toBeSelectedPageIndex]];
	if (toBeSelectedTopButton != nil) {
		TopCategoryButton *selectedTopButton = currentSelectedTopCategoryButton;		
		if (![selectedTopButton isEqual:toBeSelectedTopButton]) {
			
			currentSelectedTopCategoryButton = toBeSelectedTopButton;
			
			[toBeSelectedTopButton toSelectedState];
			[selectedTopButton toUnselectedState];
			
			topCategoryLabel.text = currentSelectedTopCategoryButton.category.name;
			
			// initilize sub categories
			[self initSubCategoryButtons:toBeSelectedTopButton.category];
		}
	}
	
	// switch sub category buttons
	SubCategoryButton *toBeSelectedSubButton = [subCategoryButtonDic objectForKey:
											[NSNumber numberWithInt:toBeSelectedPageIndex]];
	if (toBeSelectedSubButton != nil) {
		SubCategoryButton *selectedSubButton = currentSelectedSubCategoryButton;
		if (selectedSubButton == nil) {
			currentSelectedSubCategoryButton = toBeSelectedSubButton;
			[toBeSelectedSubButton toSelectedState];
		} else {
			if (![selectedSubButton isEqual:toBeSelectedSubButton]) {
				currentSelectedSubCategoryButton = toBeSelectedSubButton;
				[toBeSelectedSubButton toSelectedState];
				[selectedSubButton toUnselectedState];
			}
		}
	}
}

-(void)jumpToPage:(int)pageIndex {
	PageViewController *pageViewController = [self getPageViewControllerByPageNum:pageIndex];
	if (pageViewController != nil) {
		currentPageViewController = pageViewController;
		currentPageIndex = pageIndex;
		[self switchButton:pageIndex];
		
		[self scrollToPage];
	}
}

// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (void)dealloc {
	[scrollablePageViewControllerArray release];
	[topCategoryButtonDic release];
	[subCategoryButtonDic release];
	[pageViewControllerDic release];
    [super dealloc];
}

- (IBAction)completeOrder:(id)sender{
	NSLog(@"completeOrder");
	[self.view removeFromSuperview];
}

@end
